<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <!-- 头部定位搜索导航组件 -->
      <top-search type="primary" :location-city="locationCity.SortName" @showAreaSelect="showAreaSelect" @search="search" />
      <div class="has-top" />

      <!-- 广告轮播图 -->
      <van-swipe :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="(item, index) in swiperImg" :key="index">
          <!-- <img class="van-swipe-item__img" v-lazy="item" alt="swiper" /> -->
          <a v-if="item.Link" :href="item.Link">
            <van-image
              v-lazy
              width="100%"
              height="5rem"
              :src="item.ImgUrl ? $webInfo.ImgDomain + item.ImgUrl : ''"
              :alt="item.Title"
              fit="cover"
            />
          </a>
          <van-image
            v-if="!item.Link"
            v-lazy
            width="100%"
            height="5rem"
            :src="item.ImgUrl ? $webInfo.ImgDomain + item.ImgUrl : ''"
            :alt="item.Title"
            fit="cover"
          />
        </van-swipe-item>
      </van-swipe>

      <!-- 分类选择 -->
      <div class="index-type pd-10">
        <ul class="flex flex-wrap">
          <li v-for="(item, index) in storeTypeList" :key="index" class="index-type-item tac" @click="toAlliance(item.Id)">
            <van-image v-lazy :src="$webInfo.ImgDomain + item.CategoryPicture" round alt="分类" />
            <p class="mb-10 toe">{{ item.CategoryName }}</p>
          </li>
        </ul>
      </div>
      <!-- 首页点评tab -->
      <van-tabs
        title-active-color="#ff435b"
        title-inactive-color="#000000"
        color="#ff435b"
        sticky
        swipeable
        animated
        :offset-top="offsetTop"
        :lazy-render="false"
        @change="tabChange"
      >
        <van-tab title="推荐商户">
          <!-- 瀑布流点评组件 -->
          <!-- <experience-list /> -->

          <!-- 商户列表 -->
          <bussiness-list
            :disabled-refresh="true"
            :is-refresh="isRefresh"
            :condition="recommendCondition"
            :list-load="listLoad"
            @listRefresh="listRefresh"
          />
        </van-tab>
        <van-tab title="附近商户">
          <bussiness-list
            :disabled-refresh="true"
            :is-refresh="isRefresh"
            :condition="aroundCondition"
            :list-load="listLoad"
            @listRefresh="listRefresh"
          />
        </van-tab>
      </van-tabs>
    </van-pull-refresh>

    <!-- 定位地址选择组件 -->
    <area-select
      v-show="AreaSelect"
      class="animated"
      :class="{ slideInRight: animated == 'slideIn', slideOutRight: animated == 'slideOut' }"
      :current-city="currentCity"
      :client-width="clientWidth"
      @closeAreaSelect="closeAreaSelect"
      @selCity="selCity"
      @getCurrentPosition="getCurrentPosition"
    />

    <div class="has-bottom" />
    <!-- 底部Nav组件 -->
    <nav-bottom />
  </div>
</template>

<script>
import TopSearch from 'components/Search'
import areaSelect from 'components/areaSelect'
import NavBottom from 'components/TabBar'
import experienceList from 'components/experienceList'
import bussinessList from 'components/bussinessList'
import { getStoreCategoryTreeList } from 'api/storeCategory'
import { getListIndex } from 'api/ad'

export default {
  components: {
    TopSearch,
    areaSelect,
    NavBottom,
    experienceList,
    bussinessList
  },
  props: {
    clientWidth: {
      type: Number,
      default: document.body.clientWidth
    }
  },
  data() {
    return {
      locationCity: {
        Id: 0,
        Name: '',
        SortName: '定位中...'
      },
      // 初始化定位flag
      locationInit: false,
      currentCity: {
        Id: 0,
        Name: '',
        SortName: '定位中...'
      },
      AreaSelect: false,
      // 下拉刷新
      isLoading: false,
      isRefresh: false,
      animated: '',
      // 广告轮播图片
      swiperImg: [
        'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2702277049,3026428466&fm=26&gp=0.jpg',
        'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565268519381&di=ccf41215b011a61be3823bd448f8c32e&imgtype=0&src=http%3A%2F%2Fp1.meituan.net%2Fdpdeal%2F3c3791872cf5f279e0683519b00d1188615330.jpg',
        'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565268541443&di=b0b159a2201b3eb5c938ee99a3de0073&imgtype=0&src=http%3A%2F%2Fpic43.nipic.com%2F20140714%2F11049178_141829549001_2.jpg',
        'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565268623275&di=6155007e1b3a977fd72cc2fae7b35eaa&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F73537f118ccb2540ac0a49e2cb57cd74469444c2a608a-yNTFeJ_fw658'
      ],
      storeTypeList: [],
      // 商家分页条件
      recommendCondition: {
        IsRecommend: 1,
        SortType: 1,
        PageIndex: 1,
        PageSize: 20,
        SearchKey: ''
      },
      aroundCondition: {
        IsRecommend: -1,
        SortType: 1,
        PageIndex: 1,
        PageSize: 20,
        SearchKey: ''
      },
      // 允许列表加载(在定位成功或失败后设置true)
      listLoad: false
    }
  },
  computed: {
    offsetTop() {
      return parseInt((this.clientWidth / this.$remUnit) * 10) // 设置粘性布局时距离顶部距离PX换算
    }
  },
  created() {
    // 获取分类列表
    this.getStoreCategoryTreeList()
    // 获取广告轮播
    this.getListIndex()
    // 获取当前定位
    this.getCurrentPosition()
  },
  activated() {},
  methods: {
    // 下拉刷新
    onRefresh() {
      if (this.listLoad) {
        this.isRefresh = true
      } else {
        this.isLoading = false
      }
    },
    // 列表刷新后的回调
    listRefresh() {
      this.isRefresh = false
      this.isLoading = false
    },
    // 显示地址选择
    showAreaSelect(val) {
      const self = this
      self.animated = 'slideIn'
      self.AreaSelect = val
      setTimeout(() => {
        self.animated = ''
        ModalHelper.afterOpen()
      }, 300)
    },
    // 关闭地址选择
    closeAreaSelect(val) {
      const self = this
      self.animated = 'slideOut'
      setTimeout(() => {
        self.AreaSelect = val
        self.animated = ''
        ModalHelper.beforeClose()
      }, 300)
    },
    // 选择城市回调
    selCity(item) {
      // console.log(item);
      if (this.locationCity.Id != item.Id) {
        this.locationCity = item
        // 手动选择城市后不再进行定位初始化
        this.locationInit = true
        this.listLoad = true
        this.recommendCondition.CityId = this.locationCity.Id
        this.aroundCondition.CityId = this.locationCity.Id
        this.onRefresh()
      }
    },
    // 获取轮播广告
    getListIndex() {
      getListIndex(-1, -1).then(res => {
        // console.log(res);
        if (res) {
          this.swiperImg = res.Data
        }
      })
    },
    // 获取商户分类
    getStoreCategoryTreeList() {
      getStoreCategoryTreeList(0).then(res => {
        // console.log(res);
        if (res) {
          this.storeTypeList = res.Data
        }
      })
    },
    // 关键字搜索商户列表
    search(key) {
      // console.log(key);
      this.recommendCondition.SearchKey = key
      this.aroundCondition.SearchKey = key
      this.onRefresh()
    },
    // Tab切换
    tabChange(name, title) {
      // console.log(name);
      // console.log(title);
    },
    // 查看相应分类联盟
    toAlliance(id) {
      this.$router.replace({
        name: 'alliance',
        params: {
          typeId: id
        }
      })
    },
    // 监听定位
    getCurrentPosition() {
      this.currentCity.SortName = '定位中...'
      // 对查询条件经纬度赋值0 0
      delete this.recommendCondition.Lng
      delete this.recommendCondition.Lat
      delete this.aroundCondition.Lng
      delete this.aroundCondition.Lat
      // 定位
      this.$geolocation.getCurrentPosition()
      AMap.event.addListener(this.$geolocation, 'complete', this.onComplete)
      AMap.event.addListener(this.$geolocation, 'error', this.onError)
    },
    // 定位成功
    onComplete(data) {
      console.log(data)
      // 截取市级ID
      this.currentCity.Id = parseInt(data.addressComponent.adcode.substr(0, 4) + '00')
      this.currentCity.Name = data.addressComponent.city
      this.currentCity.SortName = data.addressComponent.city.replace('市', '')

      // 对查询条件经纬度赋值
      this.recommendCondition.Lng = data.position.lng
      this.recommendCondition.Lat = data.position.lat
      this.aroundCondition.Lng = data.position.lng
      this.aroundCondition.Lat = data.position.lat
      this.$store.dispatch('user/setLocation', data.position)

      // 第一次初始化定位城市
      if (!this.locationInit) {
        this.locationCity.Id = parseInt(data.addressComponent.adcode.substr(0, 4) + '00')
        this.locationCity.Name = data.addressComponent.city
        this.locationCity.SortName = data.addressComponent.city.replace('市', '')
        // this.bussinessCondition.CityId = this.locationCity.Id;
        this.locationInit = true
        this.listLoad = true
        this.isRefresh = true
        // console.log(this.locationCity);
      }
    },
    // 定位失败
    onError(data) {
      console.log(data)
      this.$toast.fail({
        message: '获取定位信息失败，请刷新',
        icon: 'close'
      })
      this.currentCity.SortName = '未知'
      this.locationCity.SortName = '未知'
      setTimeout(() => {
        if (!this.locationInit) {
          this.locationInit = true
          this.listLoad = true
          this.isRefresh = true
        }
      }, 2000)
    }
  },
  // 从这里去到店铺详情就需要让详情页刷新,即不缓存
  beforeRouteLeave(to, from, next) {
    // 设置下一个路由的 meta
    // to.meta.keepAlive = false;
    next()
  }
}
</script>
<style lang="scss" scoped>
.index-type {
  background: $colorBg;
}
.index-type-item {
  width: 20%;
  .van-image {
    width: 56px;
    height: 56px;
  }
}
</style>
